package com.dehui.traders.kchart;

import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.SparseArray;

import com.dehui.traders.R;
import com.dehui.traders.bean.ConstantTest;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import me.goldze.mvvmhabit.utils.KLog;

/**
 * Created by hqq on 18.4.20.
 */

public class PriceManager {

    private Context mContext;
    private DataParse mData;
    private boolean isDragChart;
    private static PriceManager priceManager;
    private MyCombinedChartX mChartVolume;
    private SparseArray<String> stringSparseArray;
    private MyXAxis xAxis;
    private MyYAxis yAxis;

    public static PriceManager getInstange(){
        if (priceManager == null)
            priceManager = new PriceManager();
        return priceManager;
    }

    public void initPrice(Context context, MyCombinedChartX chart,DataParse data,boolean isDragChart){
        mChartVolume = chart;
        mContext = context;
        mData = data;
        this.isDragChart = isDragChart;
        stringSparseArray = setXLabels();
        initChartVolume();
        initChartData();
    }

    private SparseArray<String> setXLabels() {
        SparseArray<String> xLabels = new SparseArray<>();
        xLabels.put(0, "09:30");
        xLabels.put(60, " ");
        xLabels.put(121, "11:30 13:00");
        xLabels.put(182, " ");
        xLabels.put(241, "15:00");
        return xLabels;
    }

    private void initChartData() {
        setMarkerViewButtom(mData,mChartVolume);

        if (mData == null || mData.getDatas().size() <= 0)
            mChartVolume.setNoDataText("暂无数据");

        //设置y左右两轴最大最小值
        mChartVolume.getAxisLeft().setAxisMinValue(mData.getMin());
        mChartVolume.getAxisLeft().setAxisMaxValue(mData.getMax());
        mChartVolume.getAxisRight().setAxisMinValue(mData.getPercentMin());
        mChartVolume.getAxisRight().setAxisMaxValue(mData.getPercentMax());

        //基准线
        LimitLine ll = new LimitLine(0);
        ll.setLineColor(mContext.getResources().getColor(R.color.red));
        ll.setLineWidth(0.2f);
//        ll.enableDashedLine(10f, 10f, 0f);
        mChartVolume.getAxisRight().addLimitLine(ll);
        mChartVolume.getAxisRight().setBaseValue(0);

        ArrayList<Entry> lineCJEntries = new ArrayList<>();
        ArrayList<Entry> lineJJEntries = new ArrayList<>();

        List<BarEntry> barEntries = new ArrayList<>();
        for (int i = 0, j = 0; i < mData.getDatas().size(); i++, j++) {
            MinutesBean t = mData.getDatas().get(j);

            if (t == null) {
                lineCJEntries.add(new Entry(Float.NaN, i));
                lineJJEntries.add(new Entry(Float.NaN, i));
                continue;
            }
            if (!TextUtils.isEmpty(stringSparseArray.get(i)) &&
                    stringSparseArray.get(i).contains("/")) {
                i++;
            }
            lineCJEntries.add(new Entry(mData.getDatas().get(i).cjprice, i));
            lineJJEntries.add(new Entry(mData.getDatas().get(i).avprice, i));

            barEntries.add(new BarEntry(mData.getDatas().get(i).cjprice, i));
        }

        ArrayList<ILineDataSet> sets = new ArrayList<>();
        sets.add(setLine(0, getMinutesCount(), lineCJEntries));
        sets.add(setLine(1, getMinutesCount(), lineJJEntries));
        /*注老版本LineData参数可以为空，最新版本会报错，修改进入ChartData加入if判断*/
        LineData lineData = new LineData(getMinutesCount(), sets);
        lineData.setHighlightEnabled(false);


        //需要添加一个假的bar，才能用使用自定义的高亮
        BarDataSet set = new BarDataSet(barEntries, "");
        set.setHighlightEnabled(false);
        set.setHighLightAlpha(255);
        set.setHighLightColor(mContext.getResources().getColor(R.color.marker_line_bg));
        set.setDrawValues(false);
        set.setColor(mContext.getResources().getColor(R.color.transparent));

        BarData barData = new BarData(getMinutesCount(), set);
        barData.setHighlightEnabled(true);

        CombinedData combinedData = new CombinedData(getMinutesCount());
        combinedData.setData(barData);
        combinedData.setData(lineData);
        mChartVolume.setData(combinedData);

        mChartVolume.invalidate();//刷新图

    }

    public String[] getMinutesCount() {
        return new String[242];
    }

    private void initChartVolume() {
        mChartVolume.setScaleEnabled(false);//启用图表缩放事件
        mChartVolume.setDrawBorders(true);//是否绘制边线
        mChartVolume.setBorderWidth(1);//边线宽度，单位dp
        mChartVolume.setDragEnabled(isDragChart);//启用图表拖拽事件
        mChartVolume.setScaleYEnabled(false);//启用Y轴上的缩放
        mChartVolume.setBorderColor(mContext.getResources().getColor(R.color.border_color));//边线颜色
        mChartVolume.setDescription("");//右下角对图表的描述信息
        mChartVolume.setHardwareAccelerationEnabled(true);//是否开启硬件加速
        mChartVolume.setMinOffset(1f);//设置上下内边距
        mChartVolume.setExtraOffsets(0f, 0f, 0f, 0f);//图标周围格额外的偏移量
        Legend lineChartLegend = mChartVolume.getLegend();
        lineChartLegend.setEnabled(false);//是否绘制 Legend 图例

        //x轴
        xAxis = mChartVolume.getXAxis();//控制X轴的
        xAxis.setDrawLabels(true);//是否显示X坐标轴上的刻度，默认是true
        xAxis.setDrawAxisLine(true);//是否绘制坐标轴的线，即含有坐标的那条线，默认是true
        xAxis.setDrawGridLines(true);//是否显示X坐标轴上的刻度竖线，默认是true
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//把坐标轴放在上下 参数有：TOP, BOTTOM, BOTH_SIDED, TOP_INSIDE or BOTTOM_INSIDE.
        xAxis.enableGridDashedLine(10f, 10f, 0f);//绘制成虚线，只有在关闭硬件加速的情况下才能使用
        xAxis.setYOffset(7f);//设置X轴刻度在Y坐标上的偏移

        //左边y
        yAxis = mChartVolume.getAxisLeft();
        yAxis.setLabelCount(5, false); //第一个参数是Y轴坐标的个数，第二个参数是 是否不均匀分布，true是不均匀分布
        yAxis.setDrawLabels(true);//是否显示Y坐标轴上的刻度，默认是true
        yAxis.setDrawGridLines(true);//是否显示Y坐标轴上的刻度竖线，默认是true
        /*轴不显示 避免和border冲突*/
        yAxis.setDrawAxisLine(true);//是否绘制坐标轴的线，即含有坐标的那条线，默认是true
        yAxis.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART); //参数是INSIDE_CHART(Y轴坐标在内部) 或 OUTSIDE_CHART(在外部（默认是这个）)
        yAxis.setStartAtZero(false); //设置Y轴坐标是否从0开始
        yAxis.setShowOnlyMinMax(false); //参数如果为true Y轴坐标只显示最大值和最小值
        yAxis.enableGridDashedLine(10f, 10f, 0f); //虚线表示Y轴上的刻度竖线(float lineLength, float spaceLength, float phase)三个参数，1.线长，2.虚线间距，3.虚线开始坐标  当setDrawGridLines为true才有用

        //右边
        MyYAxis yAxisRight = mChartVolume.getAxisRight();
        yAxisRight.setLabelCount(5, false);//参考上面
        yAxisRight.setDrawLabels(false);//参考上面
        yAxisRight.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
//        axisRightPrice.setStartAtZero(false);//参考上面
        yAxisRight.setDrawGridLines(false);//参考上面
        yAxisRight.setDrawAxisLine(true);//参考上面

        xAxis.setXLabels(stringSparseArray);

    }

    @NonNull
    private LineDataSet setLine(int type, String[] xVals, ArrayList<Entry> lineEntries) {
        LineDataSet lineDataSetMa = new LineDataSet(lineEntries, "ma" + type);
//        lineDataSetMa.setMode(LineDataSet.Mode.LINEAR);
        lineDataSetMa.setHighlightEnabled(false);
        lineDataSetMa.setDrawValues(false);
        if (type == 0) {
            lineDataSetMa.setDrawFilled(true);
            lineDataSetMa.setAxisDependency(YAxis.AxisDependency.LEFT);
            lineDataSetMa.setColor(mContext.getResources().getColor(R.color.minute_blue));
        } else if (type == 1) {
            lineDataSetMa.setAxisDependency(YAxis.AxisDependency.RIGHT);
            lineDataSetMa.setColor(mContext.getResources().getColor(R.color.minute_yellow));
        } else {
            lineDataSetMa.setAxisDependency(YAxis.AxisDependency.RIGHT);
            lineDataSetMa.setColor(mContext.getResources().getColor(R.color.transparent));
        }
        lineDataSetMa.setAxisDependency(YAxis.AxisDependency.LEFT);
        lineDataSetMa.setLineWidth(1f);

        lineDataSetMa.setDrawCircles(false);
        lineDataSetMa.setAxisDependency(YAxis.AxisDependency.LEFT);

        return lineDataSetMa;
    }

    private void setMarkerViewButtom(DataParse mData, MyCombinedChartX combinedChart) {
        MyLeftMarkerView leftMarkerView = new MyLeftMarkerView(mContext, R.layout.mymarkerview);
        MyHMarkerView hMarkerView = new MyHMarkerView(mContext, R.layout.mymarkerview_line);
        MyBottomMarkerView bottomMarkerView = new MyBottomMarkerView(mContext, R.layout.mymarkerview);
        combinedChart.setMarker(leftMarkerView, bottomMarkerView, hMarkerView, mData);
    }

    public void changeData() {
        JSONObject object = null;
        try {
            object = new JSONObject(ConstantTest.MINUTESURL);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mData.parseMinutes(object);
//        initChartVolume();
        initChartData();
    }

}
